package org.snake.nebulae.emulation;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.snake.nebulae.core.task.CoreServiceTask;
import org.snake.nebulae.core.task.CoreTask;
import org.snake.nebulae.core.task.HeartBeatTask;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class FruitsServiceTask extends CoreServiceTask {

    @Resource
    private ThreadPoolTaskScheduler threadPoolTaskScheduler;

    private HeartBeatTask heartBeatTask;

    @Override
    public void createServiceInfo() {
        serviceInfo.setName("fruitService");

        serviceInfo.setServiceId(RandomUtil.randomString(2) + System.currentTimeMillis());

        serviceInfo.setServicePath(StrUtil.format("{}{}/{}/{}", CoreTask.topicPrefixShare, CoreTask.topicServices, serviceInfo.getName(), serviceInfo.getServiceId()));

        serviceInfo.setRegisterTime(System.currentTimeMillis());

        serviceInfo.setLastHeartBeatTime(System.currentTimeMillis());
    }

    @Override
    public void doRegisterServiceHandle() {
        // 构建所有提供服务的handle
        FruitsServiceHandle fruitsServiceHandle = new FruitsServiceHandle(mqttAsyncClient, serviceInfo, objectMapper);
        dispatcherHandle.register(fruitsServiceHandle);

        serviceInfo.getMethods().add(fruitsServiceHandle.getMethodName());
    }

    @Override
    public void doPluginTask() {
        this.heartBeatTask = new HeartBeatTask(serviceStartSuccess, threadPoolTaskScheduler, mqttAsyncClient, objectMapper, serviceInfo);
    }
}
